package com.shenjian.settings.controller;

import com.shenjian.commons.utils.DataUtil;
import com.shenjian.commons.utils.MD5Util;
import com.shenjian.commons.utils.Result;
import com.shenjian.settings.entity.User;
import com.shenjian.settings.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Date;

@RestController
@RequestMapping("/auth")
public class LoginController {

    @Autowired
    private UserService userService;

    /*登陆用post请求,因为数据在请求航里*/

    /**
     * 登陆方法
     *
     * @param loginAct 登陆账号
     * @param loginPwd 登陆密码
     * @param session  用来保存域对象
     * @return
     */
    @PostMapping("/login")
    public Result login(String loginAct, String loginPwd, HttpSession session) {
        //在登录界面,根据用户提交账号查询账号是否存在
        User loginUser = userService.queryByLoginAct(loginAct);

        if (loginUser == null) {
            return Result.error(-2, "登录用户不存在");
        }
        if (!loginUser.getLoginPwd().equals(MD5Util.getMD5(loginPwd))) {
            return Result.error(-3, "登录密码错误");
        }

        if ("0".equals(loginUser.getLockState())) {
            return Result.error(-4, "用户已被冻结,请联系客服");
        }

        //获取失效时间
        String expireTime = loginUser.getExpireTime();
        if (StringUtils.hasLength(expireTime) && new Date().compareTo(DataUtil.formatString(expireTime)) > 0) {

            return Result.error(-5, "当前账号有限期已过,请重新申请");
        }
        //没有问题,则登陆成功
        session.setAttribute("loginUser", loginUser);
        return Result.success(loginUser);
    }

    @GetMapping("/logout")
    public Result logout(HttpSession session) {
        //登出删除域对象
        session.removeAttribute("loginUser");
        //会话失效
        session.invalidate();
        return Result.success();
    }

}
